$(function () {
    formObj.init();
});

var formObj = new function () {
    'use strict';
    return {
        dataGrid: null,
        form: null,
        type: null,
        iId: 0,
        params: {
            schoolId: null,
            sExtra: null,
        },
        init: function () {
            this.type = xhTool.getQuery('iType');
            this.iId = xhTool.getQuery('iId');
            this.form = new xhForm($('#xh_form'));
            this.form.parse().bindRequired($('#bt_modal_confirm,parent.document'));
            if (this.type != 8) {
                var schoolArr = [{id: '0', text: '请选择'}];
                var studentArr = [{id: '0', text: '请选择'}];

                $.each(SchoolList, function (id, value) {
                    schoolArr.push({id: id, text: value});
                });
                $('[name=iSchoolId]').select2({
                    data: schoolArr,
                });
                if(this.type != 9) {
                    $('[name=iStudId]').select2({
                        data: studentArr,
                    });
                }
            }

            if (this.type == 6) {
                $('#sLeadPosition').val(applyInfo.sLeadPosition);
                $('#sLeadName').val(applyInfo.sLeadName);
                $('#sLeadPhone').val(applyInfo.sLeadPhone);
            }
            if (this.type == 8) {
                $('#sLeadPosition').val(applyInfo.sLeadPosition);
                $('#sStudName').val(applyInfo.sStudName);
                $('#sLeadPhone').val(applyInfo.sLeadPhone);
                $('#sLeadCompany').val(applyInfo.sLeadCompany);
            }
            if (this.type == 9) {
                $('#sIdentityNum').val(applyInfo.sIdentityNum);
                $('#sStudName').val(applyInfo.sStudName);
                $('#sAccountNum').val(applyInfo.sAccountNum);
            }

            var path = [];
            var con = [];
            if (ifEdit) {
                var sAttachmentUrl = applyInfo.sAttachmentUrl;
                var data = JSON.parse(sAttachmentUrl);
                if (data) {
                    $.each(data, function (id, value) {
                        if (Array.isArray(value)) {
                            path[id] = value;
                            con[id] = [];
                            $.each(value, function (k, v) {
                                var imgUrl = '<input name = "sAttachmentUrl[' + id + '][]" class="file' + id + '" type="hidden" value="' + v + '" />';
                                $('#' + id).before(imgUrl);
                                var num = v.lastIndexOf('.');
                                var nameNum = v.lastIndexOf('/');
                                var name = v.slice(nameNum + 1)
                                var str = v.slice(num + 1).toLowerCase();
                                var text = ['txt'];
                                var image = ['jpg', 'jpeg', 'png', 'gif', 'bpm'];
                                var office = ['doc', 'xls', 'ppt', 'xlsx', 'docx'];
                                var pdf = ['pdf'];
                                if (text.indexOf(str) != -1) {
                                    con[id].push({
                                        type: "text",
                                        caption: name,
                                        url: baseUrl + "school_apply/delFile",
                                        key: k + 1
                                    });
                                }
                                if (image.indexOf(str) != -1) {
                                    con[id].push({
                                        type: "image",
                                        caption: name,
                                        url: baseUrl + "school_apply/delFile",
                                        key: k + 1
                                    });
                                }
                                if (office.indexOf(str) != -1) {
                                    con[id].push({
                                        type: "other",
                                        caption: name,
                                        url: baseUrl + "school_apply/delFile",
                                        key: k + 1
                                    });
                                }
                                if (pdf.indexOf(str) != -1) {
                                    con[id].push({
                                        type: "pdf",
                                        caption: name,
                                        url: baseUrl + "school_apply/delFile",
                                        key: k + 1
                                    });
                                }
                            });
                        } else {
                            var imgUrl = '<input name = "sAttachmentUrl[' + id + '][]" class="file' + id + '" type="hidden" value="' + value + '" />';
                            $('#' + id).after(imgUrl);
                            var num = value.lastIndexOf('.');
                            var nameNum = value.lastIndexOf('/');
                            var name = value.slice(nameNum + 1)
                            var str = value.slice(num + 1).toLowerCase();
                            var text = ['txt'];
                            var image = ['jpg', 'jpeg', 'png', 'gif', 'bpm'];
                            var office = ['doc', 'xls', 'ppt', 'xlsx', 'docx'];
                            var pdf = ['pdf'];
                            if (text.indexOf(str) != -1) {
                                con.push({type: "text", caption: name, url: baseUrl + "school_apply/delFile", key: 1});
                            }
                            if (image.indexOf(str) != -1) {
                                con.push({type: "image", caption: name, url: baseUrl + "school_apply/delFile", key: 1});
                            }
                            if (office.indexOf(str) != -1) {
                                con.push({type: "other", caption: name, url: baseUrl + "school_apply/delFile", key: 1});
                            }
                            if (pdf.indexOf(str) != -1) {
                                con.push({type: "pdf", caption: name, url: baseUrl + "school_apply/delFile", key: 1});
                            }
                        }
                    });
                }
                if (applyInfo.iSchoolId != 0) {
                    $('[name=iSchoolId]').val(applyInfo.iSchoolId).trigger('change');
                    this.funObj().getStudentData(applyInfo.iSchoolId);
                }
                if (this.type == 1) {
                    $('#iTypeExpansion').val(applyInfo.iTypeExpansion);
                    if (applyInfo.iTypeExpansion == 2) {
                        $('#iDev').show();
                        $('#iDevCost').val(applyInfo.dDevCost);
                        $('#iSerCost').val(applyInfo.dSerCost);
                    }
                    this.funObj().uploadFile('tch_img', path['tch_img'], con['tch_img']);
                    this.funObj().uploadFile('relation_img', path['relation_img'], con['relation_img']);
                }
                if (this.type == 2) {
                    $('#iTypeExpansion').val(applyInfo.iTypeExpansion);
                    this.funObj().uploadFile('family_img', path['family_img'], con['family_img']);
                    this.funObj().uploadFile('stud_img', path['stud_img'], con['stud_img']);
                    this.funObj().uploadFile('borrow_img', path['borrow_img'], con['borrow_img']);
                }
                if (this.type == 5) {
                    this.funObj().uploadFile('leader_img', path['leader_img'], con['leader_img']);
                }
                if (this.type == 7) {
                    this.funObj().uploadFile('grant_img', path['grant_img'], con['grant_img']);
                }
                if (financeEdit == 1) {
                    this.funObj().uploadFile('finance_img', path['finance_img'], con['finance_img']);
                }

            } else {
                this.funObj().uploadFile('tch_img', path['tch_img'], con['tch_img']);
                this.funObj().uploadFile('relation_img', path['relation_img'], con['relation_img']);
                this.funObj().uploadFile('family_img', path['family_img'], con['family_img']);
                this.funObj().uploadFile('stud_img', path['stud_img'], con['stud_img']);
                this.funObj().uploadFile('borrow_img', path['borrow_img'], con['borrow_img']);
                this.funObj().uploadFile('leader_img', path['leader_img'], con['leader_img']);
                this.funObj().uploadFile('finance_img', path['finance_img'], con['finance_img']);
                this.funObj().uploadFile('grant_img', path['grant_img'], con['grant_img']);
            }

            this.listener();
        },
        listener: function () {
            var $this = this;
            // 提交申请单
            $('#bt_form_add').click(function () {
                $this.funObj().saveApply();
            });
            $('#bt_form_close').click(function () {
                window.top.xhTop.closeActiveTab();
            });
            $('#iTypeExpansion').on('change', function () {
                var iTchChild = $(this).val();
                if (iTchChild == 2) {
                    $('#iDev').show()
                } else {
                    $('#dSerCost').val(0);
                    $('#dDevCost').val(0);
                    $('#iDev').hide();
                }
            });
            $('[name=iSchoolId]').change(function () {
                var iSchoolId = $(this).val();
                $('[name=iStudId]').empty();
                if (iSchoolId != 0) {
                    $this.funObj().getStudentData(iSchoolId);
                    // 获取当前学校对应的学生
                } else {
                    var studentArr = [{id: '0', text: '请选择'}];
                    $('[name=iStudId]').select2({
                        data: studentArr
                    })
                }
            });
        },
        funObj: function () {
            var $this = this;
            return {
                //保存按钮处理事件
                saveApply: function () {
                    if ($this.type != 8) {
                        if ($('#iSchoolId').val() == 0) {
                            $this.funObj().initeVal('学校不能为空');
                            return false;
                        }
                        if ($('#iStudId').val() == 0) {
                            $this.funObj().initeVal('申请人不能为空');
                            return false;
                        }
                    }

                    if (typeof ($('#iTypeExpansion').val()) != "undefined") {
                        if ($('#iType').val() == 1) {
                            if ($('#iTypeExpansion').val() == 1) {
                                $this.funObj().initeVal('请选择教师子女类型');
                                return false;
                            }
                        } else if ($('#iType').val() == 0) {
                            $this.funObj().initeVal('请选择贫困生等级');
                            return false;
                        }
                    }
                    if ($this.type == 6) {
                        if (!$('#sLeadName').val()) {
                            $this.funObj().initeVal('姓名不能为空');
                            return false;
                        }
                        if (!$('#sLeadPosition').val()) {
                            $this.funObj().initeVal('职务不能为空');
                            return false;
                        }
                        if (!$('#sLeadPhone').val()) {
                            $this.funObj().initeVal('联系电话不能为空');
                            return false;
                        }
                    }
                    if ($this.type == 8) {
                        if (!$('#sLeadCompany').val()) {
                            $this.funObj().initeVal('单位名称不能为空');
                            return false;
                        }
                        if (!$('#sLeadPosition').val()) {
                            $this.funObj().initeVal('职务不能为空');
                            return false;
                        }
                        if (!$('#sLeadPhone').val()) {
                            $this.funObj().initeVal('联系电话不能为空');
                            return false;
                        }
                        if (!$('#sStudName').val()) {
                            $this.funObj().initeVal('姓名不能为空');
                            return false;
                        }

                    }
                    var input = $('input[type=file]');
                    var error = '';
                    // 判断证明是否为空
                    for (var i = 0; i < input.length; i++) {
                        var msg = '';
                        switch (input[i].id) {
                            case 'tch_img':
                                msg = '教师证';
                                break;
                            case 'relation_img':
                                msg = '出生证/户口本';
                                break;
                            case 'family_img':
                                msg = '家庭贫困证明';
                                break;
                            case 'stud_img':
                                msg = '学生贫困证明';
                                break;
                            case 'borrow_img':
                                msg = '平板借用协议';
                                break;
                            // case 'finance_img':
                            //     msg = '财务附件';
                            //     break;
                            case 'leader_img':
                                msg = '领导证明';
                                break;
                            case 'leader_img':
                                msg = '平板发放附件';
                                break;
                        }
                        if ($('input[name="sAttachmentUrl[' + input[i].id + '][]"').length == 0 && msg != '') {
                            error = '请选择并点击上传' + msg;
                            $this.funObj().initeVal(error);
                            return false;
                        }

                    }

                    $this.form.submit('school_apply/saveStudentApply', {}, function (res) {
                        if (xhExtra.checkError(res)) {
                            return false;
                        } else {
                            window.top.xhTop.showSuccess(res.msg);
                            window.top.xhTop.getFrameByName('特殊申请').obj.applyList.reload();
                            window.top.xhTop.closeActiveTab();
                        }

                    }, {check: false});
                },
                //验证报错返回s
                initeVal: function (message) {
                    window.top.xhTop.showMessage({type: 'error', title: message});
                    xhExtra.setBtnNormal($('#bt_modal_confirm', window.top.document));
                },
                getStudentData: function (iSchoolId) {
                    if ($this.type == 5) {
                        var url = 'school_apply/getContractBySchoolId';
                    } else {
                        var url = 'school_apply/getStudent';
                    }
                    xhExtra.ajaxRequest(url, {schoolId: iSchoolId}, {}, function (data) {
                        var stuArr = [{id: '0', text: '请选择'}];
                        $.each(data, function (id, value) {
                            stuArr.push({id: id, text: value});
                        });
                        $('[name=iStudId]').select2({
                            data: stuArr
                        }).on('change', function () {
                            var iStudId = $(this).val();
                            $('[name=sStudName]').val(data[iStudId]);
                        });
                        if (applyInfo.iStudId != 0) {
                            $('[name=iStudId]').val(applyInfo.iStudId).trigger('change');
                        }
                    });
                },
                uploadFile: function (eleid, path, con) {
                    $("#" + eleid).fileinput('destroy').fileinput({
                        language: 'zh', //设置语言
                        uploadUrl: baseUrl + 'school_apply/uploadFile',
                        allowedFileExtensions: ['jpg', 'jpeg', 'png', 'gif', 'bpm'],//接收的文件后缀
                        //编辑已成功上传过的图片
                        overwriteInitial: false,
                        initialPreviewAsData: true,
                        initialPreviewFileType: 'image',
                        initialPreview: path, //要显示的图片的路径
                        initialPreviewConfig: con,
                        initialPreviewShowDelete: true,
                        //
                        previewSettings: 600,
                        allowedPreviewTypes: ['image'],
                        uploadAsync: true, //默认异步上传
                        showUpload: true, //是否显示上传按钮
                        showCaption: false,//是否显示标题
                        dropZoneEnabled: false,
                        browseClass: "btn btn-primary", //按钮样式
                        maxFileSize: 50000,
                        maxFileCount: 10, //表示允许同时上传的最大文件个数
                        enctype: 'multipart/form-data',
                        validateInitialCount: true,
                        height: 200,
                        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
                        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！"
                    });

                    $("#" + eleid).on("fileuploaded", function (event, data, previewId, index) {
                        var url = data.response.msg.url;
                        var fileUrl = '<input name = "sAttachmentUrl[' + eleid + '][]" class="file' + eleid + '" type="hidden" value="' + url + '" />';
                        $('#' + eleid).before(fileUrl);
                    });

                    $("#" + eleid).on("filesuccessremove", function (event, id) {
                        var num = id.lastIndexOf('-');
                        var str = id.slice(num + 1);
                        $('input[name="sAttachmentUrl[' + eleid + '][]"').eq(str).remove();
                    });
                    $("#" + eleid).on("filedeleted", function (event, key, jqXHR, data) {
                        $('input[name="sAttachmentUrl[' + eleid + '][]"').eq(key - 1).remove();
                    });

                }
            }
        }
    }
};